<?php

/**
 * Controller is the customized base controller class.
 * All controller classes for this application should extend from this base class.
 */
class Controller extends CController {

    /**
     * @var string the default layout for the controller view. Defaults to '//layouts/column1',
     * meaning using a single column layout. See 'protected/views/layouts/column1.php'.
     */
    public $layout = '//layouts/main2';

    /**
     * @var array context menu items. This property will be assigned to {@link CMenu::items}.
     */
    public $menu = array();

    /**
     * @var array the breadcrumbs of the current page. The value of this property will
     * be assigned to {@link CBreadcrumbs::links}. Please refer to {@link CBreadcrumbs::links}
     * for more details on how to specify this property.
     */
    public $breadcrumbs = array();
    public static $pageData;
    public static $pageInfo;
    public static $pageType;
    public static $filter;

    protected function getPageInfo() {
        return self::$pageInfo;
    }

    public function filterPages() {
        return !empty(self::$pageInfo) ? true : false;
    }

    public function getBreadcrumbs() {
        if (self::$pageInfo) {
            $breadCrumbs['Главная'] = '/';
            foreach (self::$pageInfo as $page) {
                $breadCrumbs[$page['r_ch_title']] = $page['r_ch_url'];
            }
        }
        return isset($breadCrumbs) ? $breadCrumbs : false;
    }

    protected function beforeAction($event) {
        if (empty(Yii::app()->session['region'])) {
            $regions = Yii::app()->params['regions'];
            $ip = $this->getUserIp();
            $gb = new IPGeoBase();
            $data = $gb->getRecord($ip);
            if (!empty($data)) {
                array_walk_recursive($data, function(&$value, $key) {
                    $value = iconv("CP1251", "UTF-8", $value);
                });
                foreach ($regions as $region) {
                    if (stripos($region['regionTitle'], $data['city']) !== false) {
                        $this->setRegion($region['id']);
                        break;
                    }
                }
            }
        }
        return true;
    }

    public function getUserIp() {
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (!empty($_SERVER['HTTP_X_REAL_IP'])) {
            $ip = $_SERVER['HTTP_X_REAL_IP'];
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ip = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
            $ip = $ip[0];
        } else {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        return trim($ip);
    }

    public function getRegion() {
        $regions = Yii::app()->params['regions'];
        return !empty(Yii::app()->session['region']) ? Yii::app()->session['region'] : $regions[1];
    }

    public function setRegion($regionID) {
        $regions = Yii::app()->params['regions'];
        Yii::app()->session['region'] = $regions[$regionID];
        if (Yii::app()->session['region'] === $regions[$regionID])
            return true;
        else
            return false;
    }

    public function sendMail($toEmail, $subject, $content, $uploadedFile = null) {
        Yii::import('application.extensions.yii-mail.YiiMailMessage');
        $message = new YiiMailMessage;
        $message->setBody($content, 'text/html');
        $message->subject = $subject;
        $message->addTo($toEmail);
        $message->from = 'no-reply@mobi03.ru';

        if ($uploadedFile !== NULL) {
            $message->attach(Swift_Attachment::fromPath($uploadedFile->tempName)->setFilename($uploadedFile->name));
        }
        Yii::app()->mail->send($message);
    }

    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'order-form') {
            $model->scenario = $model->method == 'deliv' ? 'ship' : 'deliv';
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    public function getDeliveryTime($time) {
        $str = '';
        $seconds = $time * 60;
        $current = time();
        $delivery = $seconds + $current;
        $max = $delivery - $current;
        $day = intval($max / 60 / 60 / 24);
        $hour = intval(($max - $day * 60 * 60 * 24) / 60 / 60);
        $minut = intval(($max - $day * 60 * 60 * 24 - $hour * 60 * 60) / 60);
        $ec = intval($max - $day * 60 * 60 * 24 - $hour * 60 * 60 - $minut * 60);
        
        $days = array('Sunday' => 'воскресенье', 'Monday' => 'понедельник', 'Tuesday' => 'вторник', 'Wednesday' => 'среда', 'Thursday' => 'четверг', 'Friday' => 'пятница', 'Saturday' => 'суббота');
   
        if ($day == 0)
            $str = 'Сегодня после ' . date('H:00', $delivery);
        else if ($day == 1)
            $str = 'Завтра (' . date('d.m', $current + 24 * 60 * 60) . ' ' . $days[date('l', $current + 24 * 60 * 60)] . ')';
        else if ($day == 2)
            $str = 'После завтра (' . date('d.m', $current + 48 * 60 * 60) . ' ' . $days[date('l', $current + 48 * 60 * 60)] . ')';
        else
            $str = date('d.m', $delivery) . ', ' . $days[date('l', $delivery)] . ' после ' . date('H:00', $delivery);



        return $str;
    }

}
